import 'dart:convert';
import 'dart:io';

import 'package:PollOnLine/bean/UserTaskDetail.dart';
import 'package:PollOnLine/bean/UserTaskWrite.dart';
import 'package:PollOnLine/manager/UserInfoManager.dart';
import 'package:PollOnLine/utils/DialogUtils.dart';
import 'package:PollOnLine/utils/logger_utils.dart';
import 'package:PollOnLine/utils/path_provider_utils.dart';
import 'package:PollOnLine/utils/permission_utils.dart';
import 'package:PollOnLine/values/CommonParam.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../bean/FileRes.dart';
import '../../../bean/request/SaveTaskFile.dart';
import '../../../network/UrlPath.dart';
import '../../../network/network.dart';
import '../../../utils/EventBusUtils.dart';
import '../../../utils/amap_utils.dart';
import '../../../utils/path_utils.dart';
import '../../../utils/toast_utils.dart';
import '../../../utils/utils.dart';
import '../../../values/MyColors.dart';
import '../add_poll/add_poll_view.dart';
import '../complete_poll/complete_poll_view.dart';
import '../complete_poll/complete_poll_view_ipad.dart';
import 'task_detail_state.dart';

class TaskDetailLogic extends GetxController {
  final TaskDetailState state = TaskDetailState();

  // 刷新控制器 initialRefresh 是否最初刷新
  late RefreshController refreshController = RefreshController(initialRefresh: false);

  late StreamSubscription<TaskDetail>? subscription;

  late String taskId;

  @override
  void onInit() {
    super.onInit();
    taskId = Get.arguments;
  }

  @override
  void onReady() {
    super.onReady();
    // 监听刷新
    subscription = bus.listen((event) => initData());
    initData();
  }

  void initData() {
    getUserTaskDetail();
    listTaskWrite();
  }

  /// 获取用户任务详情
  Future<void> getUserTaskDetail() async {
    Map<String, dynamic> param = {
      "oneParam": taskId,
    };

    ResultData resultData = await Api.getUserTaskDetail(param);
    if (resultData.isSuccess) {
      UserTaskDetail userTaskDetail = UserTaskDetail.fromJson(resultData.data['data']);
      state.questionId = userTaskDetail.questionId ?? "";
      state.status = userTaskDetail.status ?? "";
      state.taskName = userTaskDetail.taskName ?? "";
      state.title = userTaskDetail.title ?? "";
      state.taskDesc = userTaskDetail.taskDesc ?? "";
      state.endTime = userTaskDetail.endTime ?? "";
      state.updateTime = userTaskDetail.updateTime ?? "";
      state.collectCount = userTaskDetail.collectCount ?? 1;
      state.writeCount = userTaskDetail.writeCount ?? 0;
      state.validCount = userTaskDetail.validCount ?? 0;
      // state.percent = state.writeCount / state.collectCount;
      // {"position":true,"record":true,"video":true}
      String commonSet = userTaskDetail.commonSet ?? '';
      state.isPosition = jsonDecode(commonSet)['position'];
      state.isRecord = jsonDecode(commonSet)['record'];
      state.isSignature = jsonDecode(commonSet)['sign'];
      state.isVideo = jsonDecode(commonSet)['video'];
      state.isLimit = jsonDecode(commonSet)['limit'];

      state.isShowBottom = state.status == "1" || (state.status != "2" && state.isLimit);
      update();
    }
  }

  /// 获取异常样本列表
  Future<void> listTaskWrite() async {
    Map<String, dynamic> page = {
      "oneParam": taskId,
    };
    Map<String, dynamic> param = {
      "currentPage": state.currentPage,
      'pageSize': 10,
      'param': page,
    };

    ResultData resultData = await Api.listTaskWrite(param);
    if (resultData.isSuccess) {
      if (state.currentPage == 1) {
        state.taskWrite = UserTaskWrite.fromJson(resultData.data['data']);
      } else {
        state.taskWrite?.content?.addAll(UserTaskWrite.fromJson(resultData.data['data']).content as Iterable<Content>);
      }
      update();
    }
  }

  // 上拉加载更多的异常样本
  Future<void> onLoading() async {
    // 监视网络获取
    await Future.delayed(const Duration(milliseconds: 1000));
    // 如果完成使用loadFailed()，如果没有数据返回，使用LoadNodata()
    int totalPages = state.taskWrite?.totalPages ?? 1;

    if (state.currentPage < totalPages) {
      state.currentPage++;
      await listTaskWrite();
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  // 单文件上传
  Future<FileRes?> uploadFile(String filePath) async {
    String fileName = PathUtils.getName(filePath);
    late dio.MultipartFile multipartFile = dio.MultipartFile.fromFileSync(filePath, filename: fileName);
    ResultData resultData = await Api.uploadFile(multipartFile);
    if (resultData.isSuccess) {
      return FileRes.fromJson(resultData.data['data']);
    } else {
      toast.show("文件上传失败");
      bus.fire(TaskDetail());
    }
    return null;
  }

  // 保存任务文件信息
  Future<bool> saveTaskFile(String writeId, {FileRes? fileRes, LocationInfo? location}) async {
    SaveTaskFile saveTaskFile = SaveTaskFile();
    saveTaskFile.busType = BUS_TYPE_RECORD;
    if (fileRes != null) {
      List<FileRes> list = [fileRes];
      saveTaskFile.fileShowList = list;
    }
    if (state.isPosition) {
      saveTaskFile.address = location?.address;
      saveTaskFile.latitude = location?.latitude.toString();
      saveTaskFile.longitude = location?.longitude.toString();
    }
    saveTaskFile.writeId = writeId;

    ResultData resultData = await Api.saveTaskFile(saveTaskFile.toJson());
    if (resultData.isSuccess) {
      return true;
    } else {
      toast.show("保存任务文件信息失败");
      return false;
    }
  }

  /// 完成调研
  Future<void> completeWrite(String writeId) async {
    Map<String, dynamic> param = {"oneParam": writeId};
    ResultData resultData = await Api.completeWrite(param);
    if (resultData.isSuccess) {
      bus.fire(TaskList());
      bus.fire(TaskDetail());
      Get.back();
    } else {
      toast.show(resultData.data);
    }
  }

  /// 删除异常样本
  Future<void> delTaskWrite(String writeId) async {
    Map<String, dynamic> param = {"oneParam": writeId};
    ResultData resultData = await Api.delTaskWrite(param);
    if (resultData.isSuccess) {
      bus.fire(TaskList());
      bus.fire(TaskDetail());
    } else {
      toast.show(resultData.data);
    }
  }

  // 获取异样样本 异常信息
  // 录音 签名 照片和视频
  String getTaskWriteInfo(int? recordCount, int? signCount, int? videoCount) {
    String str = '缺少${state.isRecord && recordCount == 0 ? "录音、" : ""}'
        '${state.isSignature && signCount == 0 ? "签名、" : ""}'
        '${state.isVideo && videoCount == 0 ? "图片或视频、" : ""}';
    return str.substring(0, str.length - 1);
  }

  Future<void> goToAddPoll() async {
    if (state.isPosition) {
      // 定位
      if (!await PermissionUtils().getLocationState()) {
        toast.show("开启定位权限");
        return;
      }
      // 定位服务
      if (!await PermissionUtils().getLocationStatus()) {
        toast.show("开启定位服务");
        return;
      }
    }
    if (state.isVideo) {
      // 文件存储
      if (!await PermissionUtils().getStorageState()) {
        toast.show("开启文件存储权限");
        return;
      }

      if (!await PermissionUtils().getMicrophoneeState()) {
        toast.show("开启麦克风权限");
        return;
      }
    }

    String questionId = state.questionId;
    String url = '';
    if (UrlPath.baseUrl == CommonParam.DEBUG_URL) {
      url = 'http://192.168.19.122:8080/#/survey/';
    } else {
      url = '${UrlPath.baseUrl}/bt/survey/index.html#/';
    }
    url += '$questionId?taskId=$taskId&userId=${UserInfoManager().getUserId()}';
    // url = "assets/files/test.html";
    // 跳转新增样本
    Get.to(() => const AddPollPage(title: '新增样本'), arguments: url);
  }

  Future<void> goToCompletion(Content item) async {
    if (state.isRecord && item.recordCount == 0) {
      String path = '${await PathProviderUtils().getTempDir()}/${item.id}.wav';
      kLog.i(path);
      File file = File(path);
      bool exists = await file.exists();
      if (exists) {
        FileRes? fileRes = await uploadFile(path);
        await saveTaskFile(item.id!, fileRes: fileRes);
      } else {
        dialogUtils.show(
          context: Get.context!,
          title: "异常提醒",
          content: "未找到当前问卷的录音，删除当前问卷重新作答或联系管理员，是否要删除当前问卷？",
          callbackOk: () {
            delTaskWrite(item.id!);
          },
        );
        return;
      }
    }

    Map<String, dynamic> params = {
      "writeId": item.id,
      "isSignature": state.isSignature && item.signCount == 0,
      "isVideo": state.isVideo && item.videoCount == 0,
    };
    if (isPad(Get.context!)) {
      Get.to(() => const CompletePollPageIpad(title: '完成调研'), arguments: params);
    } else {
      Get.to(() => const CompletePollPage(title: '完成调研'), arguments: params);
    }
  }

  // 获取百分比
  String getPercent(int? writeCount, int? collectCount) {
    String str = '${(writeCount! / collectCount! * 1000).round() / 10.toDouble()}';
    if (str.substring(str.length - 1, str.length) == "0") {
      str = '${double.parse(str).toInt().toString()}%';
    } else {
      str = "$str%";
    }
    return str;
  }

  dynamic getStatus(String status) {
    late var str = {};
    switch (status) {
      case "1":
        str = {"tagText": "进行中", "proColor": MyColors.FF1060DD};
      case "2":
        str = {"tagText": "截止", "proColor": MyColors.FFE9961F};
      default:
        str = {"tagText": "已完成", "proColor": MyColors.FF57BB72};
    }
    return str;
  }

  @override
  void onClose() {
    super.onClose();
    subscription?.cancel();
  }
}
